package com.fdb.efp.nls.service.impl;

import com.fdb.basic.framework.core.base.FrameworkService;
import com.fdb.basic.framework.core.constant.BaseConstant;
import com.fdb.basic.framework.core.constant.SDicToExternalConstant;
import com.fdb.basic.framework.core.util.DateUtility;
import com.fdb.basic.framework.core.util.StringUtil;
import com.fdb.basic.framework.core.util.TimeUtil;
import com.fdb.basic.framework.core.util.sdic.SDicToExternal;
import com.fdb.efp.nls.common.ConsoleConstant;
import com.fdb.efp.esb.service.bo.req.basicfn.FiveLeClaManChangeReqBean;
import com.fdb.efp.esb.service.bo.resp.basicfn.FiveLeClaManChangeRespBean;
import com.fdb.efp.esb.service.facade.basicfn.FiveLeClaManChangeService;
import com.fdb.efp.flow.common.vo.PageApproveVO;
import com.fdb.efp.flow.service.facade.BizEventInfoService;
import com.fdb.efp.nls.service.facade.AccLoanService;
import com.fdb.efp.nls.service.vo.AccLoanVO;
import com.fdb.efp.nls.common.RscConstant;
import com.fdb.efp.nls.service.dao.RscAdjustAppDao;
import com.fdb.efp.nls.service.dao.RscLoanChgHisDao;
import com.fdb.efp.nls.service.dao.RscTaskLoanDao;
import com.fdb.efp.nls.service.domain.RscAdjustApp;
import com.fdb.efp.nls.service.domain.RscLoanChgHis;
import com.fdb.efp.nls.service.domain.RscTaskLoan;
import com.fdb.efp.nls.service.facade.RscAdjustRemoveApprService;
import com.fdb.efp.nls.service.vo.RscAdjustAppVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.Objects;

import static com.fdb.basic.framework.core.constant.SDicToExternalConstant.SYSID_IFP;

/**
 * <p>ServiceImpl: 风险分类调整申请表				<p>
 *
 * @author ligm
 * @date 2019-09-04
 */
@Service("rscAdjustRemoveApprService")
public class RscAdjustRemoveApprServiceImpl implements RscAdjustRemoveApprService, FrameworkService {

    private static Logger logger = LoggerFactory.getLogger(RscAdjustRemoveApprServiceImpl.class);

    @Autowired
    private RscAdjustAppDao rscAdjustAppDao;
    @Autowired
    private RscTaskLoanDao rscTaskLoanDao;
    @Autowired
    private AccLoanService accLoanService;
    @Autowired
    private RscLoanChgHisDao rscLoanChgHisDao;
    @Autowired
    @Qualifier("bizEventInfoService")
    private BizEventInfoService bizEventInfoService;
    @Autowired
    @Qualifier("fiveLeClaManChangeService")
    private FiveLeClaManChangeService fiveLeClaManChangeService;

    @Override
    public void pass(String bizSerno, PageApproveVO pageApproveVo) {
        logger.info("风险分类调整解除通过流水号" + bizSerno);
        int num = 0;
        try {
            if (Objects.nonNull(bizSerno) && !"".equals(bizSerno)) {
                RscAdjustAppVO vo = new RscAdjustAppVO();
                vo.setRscRmNo(bizSerno);
                RscAdjustApp rscAdjustApp = rscAdjustAppDao.queryByRscRmNo(vo);
                beanCopy(rscAdjustApp, vo);
                if (Objects.nonNull(vo)) {
                    vo.setLastUpdateTime(TimeUtil.getCurrentDateTime());
                    vo.setLastUpdateUser(pageApproveVo.getAprvUserId());
                    // 审批用户编号
                    vo.setAprvUserCode(pageApproveVo.getAprvUserId());
                    // 审批意见
                    vo.setAprvComment(pageApproveVo.getAprvComment());
                    // 审批状态 = 通过
                    vo.setApprStatus(ConsoleConstant.APRV_STATUS_03);
                    // 审批时间
                    vo.setApprDate(TimeUtil.getCurrentDate());
                }
                beanCopy(vo, rscAdjustApp);
                num = rscAdjustAppDao.updateByRscRmNo(rscAdjustApp);
                if(num==0){
                    logger.info("更新审批信息失败");
                    return;
                }

                //风险分类调整解除审批通过后，将调整结果告知互金
                if (!noticeIFPAdjResult(rscAdjustApp)){
                    logger.info("更新互金接口失败");
                    if (Objects.nonNull(vo)) {
                        vo.setLastUpdateTime(TimeUtil.getCurrentDateTime());
                        vo.setLastUpdateUser(pageApproveVo.getAprvUserId());
                        vo.setAprvUserCode(pageApproveVo.getAprvUserId());
                        vo.setAprvComment("【系统提示】 调用接口失败，系统已打回您的申请！");
                        vo.setApprStatus(ConsoleConstant.APRV_STATUS_05);
                        vo.setApprDate(TimeUtil.getCurrentDate());
                    }
                    beanCopy(vo, rscAdjustApp);
                    rscAdjustAppDao.updateByRscRmNo(rscAdjustApp);
                    return;
                }

                // 更新风险分类台账表
                num = 0;
                RscTaskLoan rscTaskLoan = new RscTaskLoan();
                rscTaskLoan.setBillNo(rscAdjustApp.getBillNo());
                RscTaskLoan query = rscTaskLoanDao.queryByBillNo(rscTaskLoan);
                query.setGeneWay(RscConstant.S_ZB_GENE_WAY_03);
                query.setCurrResult(rscAdjustApp.getAdjustResult());
                query.setFiveResult(rscAdjustApp.getAdjustBasic());
                query.setLastUpdateUser(pageApproveVo.getAprvUserId());
                query.setLastUpdateTime(TimeUtil.getCurrentDateTime());
                num = rscTaskLoanDao.updateByBillNo(query);
                if(num==0){
                    logger.info("更新风险分类台账表失败");
                    return;
                }

                // 更新风险分类台账变动历史表

                num = 0;
                RscLoanChgHis rscLoanChgHis = new RscLoanChgHis();
                rscLoanChgHis.setBillNo(rscAdjustApp.getBillNo());
                rscLoanChgHis.setRscAdjNo(rscAdjustApp.getRscAdjNo());
                rscLoanChgHis.setLoanAmount(rscAdjustApp.getLoanAmount());
                rscLoanChgHis.setLoanBalance(rscAdjustApp.getLoanBalance());
                rscLoanChgHis.setLoanStartDate(rscAdjustApp.getLoanStartDate());
                rscLoanChgHis.setLoanEndDate(rscAdjustApp.getLoanEndDate());
                rscLoanChgHis.setOverdueDate(rscAdjustApp.getOverdueDate());
                rscLoanChgHis.setAccountStatus(rscAdjustApp.getAccountStatus());
                rscLoanChgHis.setGeneWay(rscAdjustApp.getGeneWay());
                rscLoanChgHis.setCurrResult(rscAdjustApp.getAdjustResult());
                rscLoanChgHis.setFiveResult(rscAdjustApp.getAdjustBasic());
                rscLoanChgHis.setPrdCode(rscAdjustApp.getPrdCode());
                rscLoanChgHis.setPrdName(rscAdjustApp.getPrdName());
                rscLoanChgHis.setChannelNo(rscAdjustApp.getChannelNo());
                rscLoanChgHis.setAssureMeansMain(rscAdjustApp.getAssureMeansMain());
                rscLoanChgHis.setCusId(rscAdjustApp.getCusId());
                rscLoanChgHis.setCusName(rscAdjustApp.getCusName());
                rscLoanChgHis.setCertCode(rscAdjustApp.getCertCode());
                rscLoanChgHis.setCertType(rscAdjustApp.getCertType());
                rscLoanChgHis.setCusManager(rscAdjustApp.getCusManager());
                rscLoanChgHis.setMainBrId(rscAdjustApp.getMainBrId());
                rscLoanChgHis.setRscUpdateDate(rscAdjustApp.getApprDate());
                rscLoanChgHis.setCreateUser(pageApproveVo.getAprvUserId());
                rscLoanChgHis.setCreateTime(TimeUtil.getCurrentDateTime());
                num = rscLoanChgHisDao.insertRscLoanChgHis(rscLoanChgHis);
                if(num==0){
                    logger.info("更新风险分类台账变动历史表失败");
                    return;
                }

                // 更新贷款台账表
                num = 0;
                AccLoanVO accLoanVO = new AccLoanVO();
                accLoanVO.setBillNo(rscAdjustApp.getBillNo());
                AccLoanVO queryAcc =accLoanService.queryByPk(accLoanVO);
                if(queryAcc == null){
                    logger.info("查询贷款台账表失败");
                    return;
                }
                queryAcc.setClaPre(queryAcc.getCla());
                queryAcc.setClaDatePre(queryAcc.getClaDate());
                queryAcc.setManualIdt(RscConstant.S_ZB_GENE_WAY_03);
                queryAcc.setCla(rscAdjustApp.getAdjustResult());
                queryAcc.setClaDate(rscAdjustApp.getAppDate());
                num = accLoanService.updateByPk(queryAcc);
                if(num==0){
                    logger.info("更新贷款台账表失败");
                    return;
                }


            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void refuse(String bizSerno, PageApproveVO pageApproveVo) {
        logger.info("风险分类调整解除拒绝流水号" + bizSerno);
        try {
            if (Objects.nonNull(bizSerno) && !"".equals(bizSerno)) {
                RscAdjustAppVO vo = new RscAdjustAppVO();
                vo.setRscRmNo(bizSerno);
                RscAdjustApp rscAdjustApp = rscAdjustAppDao.queryByRscRmNo(vo);
                beanCopy(rscAdjustApp, vo);
                if (Objects.nonNull(vo)) {
                    vo.setLastUpdateTime(TimeUtil.getCurrentDateTime());
                    vo.setLastUpdateUser(pageApproveVo.getAprvUserId());
                    // 审批用户编号
                    vo.setAprvUserCode(pageApproveVo.getAprvUserId());
                    // 审批意见
                    vo.setAprvComment(pageApproveVo.getAprvComment());
                    // 审批状态 = 拒绝
                    vo.setApprStatus(ConsoleConstant.APRV_STATUS_04);
                    // 审批时间
                    vo.setApprDate(TimeUtil.getCurrentDate());
                }
                beanCopy(vo, rscAdjustApp);
                rscAdjustAppDao.updateByRscRmNo(rscAdjustApp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void repulse(String bizSerno, PageApproveVO pageApproveVo) {
        try {
            if (bizEventInfoService.isFirstNode(bizSerno)) {
                logger.info("风险分类调整解除打回流水号" + bizSerno);
                if (Objects.nonNull(bizSerno) && !"".equals(bizSerno)) {
                    RscAdjustAppVO vo = new RscAdjustAppVO();
                    vo.setRscRmNo(bizSerno);
                    RscAdjustApp rscAdjustApp = rscAdjustAppDao.queryByRscRmNo(vo);
                    beanCopy(rscAdjustApp, vo);
                    if (Objects.nonNull(vo)) {
                        vo.setLastUpdateTime(TimeUtil.getCurrentDateTime());
                        vo.setLastUpdateUser(pageApproveVo.getAprvUserId());
                        // 审批用户编号
                        vo.setAprvUserCode(pageApproveVo.getAprvUserId());
                        // 审批意见
                        vo.setAprvComment(pageApproveVo.getAprvComment());
                        // 审批状态 = 打回
                        vo.setApprStatus(ConsoleConstant.APRV_STATUS_05);
                        // 审批时间
                        vo.setApprDate(TimeUtil.getCurrentDate());
                    }
                    beanCopy(vo, rscAdjustApp);
                    rscAdjustAppDao.updateByRscRmNo(rscAdjustApp);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean noticeIFPAdjResult(RscAdjustApp rscAdjustApp){
        String adjustResult = rscAdjustApp.getAdjustResult();
        boolean result = true;
        FiveLeClaManChangeReqBean fiveLeClaManChangeReqBean = new FiveLeClaManChangeReqBean();
        //通过借据编号获取贷款号
        String loanSeq = getLoanSeq(rscAdjustApp.getBillNo());
        if(StringUtil.isNullorBank(loanSeq)){
            logger.error("通过借据编号:" + rscAdjustApp.getBillNo() + "，获取到的贷款号为空！");
            result = false;
            return result;
        }
        fiveLeClaManChangeReqBean.setAcctNo(loanSeq);
        try {
            fiveLeClaManChangeReqBean.setLoanLvl5Cl(SDicToExternal.getExternalSysDicVal(SYSID_IFP, SDicToExternalConstant.STD_ZB_FIVE_SORT, adjustResult));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("本地系统字典项转互金接口所需字典项出错，请核查配置文件(dicExternal.properties)！");
            result = false;
            return result;
        }
        // 减值处理标志 (五级分类为损失时涉及到互金的减值处理)
        if(RscConstant.STD_ZB_FIVE_SORT_30.equals(adjustResult) || RscConstant.STD_ZB_FIVE_SORT_40.equals(adjustResult) ||
                RscConstant.STD_ZB_FIVE_SORT_50.equals(adjustResult)){
            fiveLeClaManChangeReqBean.setImpmtDealFlg(BaseConstant.YES_Y);
        }else{
            fiveLeClaManChangeReqBean.setImpmtDealFlg(BaseConstant.NO_N);
        }
        // 自动变更标志
        fiveLeClaManChangeReqBean.setLoanLvl5ClAutoMdfFlg(BaseConstant.NO_N);
        // 贷款五级分类自动变更起始日期 = 生效日期 = 审批通过日期
        fiveLeClaManChangeReqBean.setLoanLvl5ClAutoMdfStrtDt(DateUtility.format10To8(rscAdjustApp.getApprDate()));
        //  贷款五级分类自动变更结束日期
        String endDt = DateUtility.format10To8(DateUtility.ADD_DAY(rscAdjustApp.getApprDate(),30));
        fiveLeClaManChangeReqBean.setLoanLvl5ClAutoMdfEndDt(endDt);
        // 贷款五级分类备注
        fiveLeClaManChangeReqBean.setLoanLvl5ClRmrk("");
        FiveLeClaManChangeRespBean fiveLeClaManChangeRespBean = new FiveLeClaManChangeRespBean();
        try {
            fiveLeClaManChangeRespBean = fiveLeClaManChangeService.applyFiveLeClaManChange(fiveLeClaManChangeReqBean);
            if(fiveLeClaManChangeRespBean == null){
                logger.info(">==========同步互金五级分类结果失败===========<");
                result = false;
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(">==========同步互金五级分类结果失败===========<" +e.getMessage());
            result = false;
            return result;
        }
        return result;
    }

    private String getLoanSeq(String billNo){
        AccLoanVO accLoanVO = new AccLoanVO();
        accLoanVO.setBillNo(billNo);
        accLoanVO = accLoanService.queryByPk(accLoanVO);
        if(Objects.isNull(accLoanVO)){
            return null;
        }
        return accLoanVO.getLoanSeq();
    }
}
